package com.qyhl.webtv.module_live.teletext;

import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.OtherDialog;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.live.TeleTextBean;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.module_live.R;
import com.qyhl.webtv.module_live.R2;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.umeng.analytics.MobclickAgent;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import es.dmoral.toasty.Toasty;

/**
 * Created by qyhl on 2017/12/14.
 * 图文直播列表页面
 */
@Route(path = ARouterPathConstant.TELETEXT_LIST)
public class TeleTextListActivity extends BaseActivity implements TeleTextListContract.TeleTextListView {
    @BindView(R2.id.title)
    TextView mTitle;
    @BindView(R2.id.listview)
    ListView listview;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.back_btn)
    ImageView backBtn;

    private TeleTextListPresenter mPresenter;

    String title;

    private List<TeleTextBean> mDataList = new ArrayList<>();

    private CommonAdapter<TeleTextBean> mAdapter;

    private String sceneId = "0";

    private String type = "0";

    private OtherDialog.Builder mDialog;

    @Override
    protected int getContentView() {
        return R.layout.live_activity_teletext_list;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new TeleTextListPresenter(this);
        loadMask.setStatus(LoadingLayout.Loading);

        title = getIntent().getStringExtra("title");
        type = getIntent().getStringExtra("type");
        if (StringUtils.isEmpty(type)) {
            type = "0";
        }

        mTitle.setText(StringUtils.isEmpty(title) ? "全媒体直播" : title);

        refresh.setEnableLoadMore(true);
        refresh.setRefreshHeader(new MaterialHeader(this));
        refresh.setRefreshFooter(new ClassicsFooter(this));
        refresh.setDisableContentWhenRefresh(true);

        mAdapter = new CommonAdapter<TeleTextBean>(this, R.layout.live_item_teletext_list, mDataList) {
            @Override
            protected void convert(ViewHolder holder, TeleTextBean item, int position) {
                holder.setText(R.id.item_live_title, item.getTitle());
                String hitCount = item.getHits();
                if (!StringUtils.isEmpty(hitCount)) {
                    holder.setText(R.id.item_live_friends, hitCount + "人参与");
                } else {
                    holder.setText(R.id.item_live_friends, "0人参与");
                }

                ImageView bg = holder.getView(R.id.item_live_logo);
                ImageView tag = holder.getView(R.id.item_live_tagtype);
                tag.setImageResource(R.drawable.icon_lives_media);
                ImageView review = holder.getView(R.id.live_status);
                Glide.with(TeleTextListActivity.this).load(item.getCoverPic()).apply(new RequestOptions().error(R.drawable.cover_large_default)).into(bg);
                //状态
                int status = Integer.parseInt(item.getStatus());
                switch (status) {
                    case 6:
                        //预告
                        review.setVisibility(View.VISIBLE);
                        review.setImageResource(R.drawable.icon_lives_live);
                        break;
                    case 7:
                        //回放
                        review.setVisibility(View.VISIBLE);
                        review.setImageResource(R.drawable.icon_lives_review);
                        break;
                    case 2:
                        //直播中
                        review.setVisibility(View.VISIBLE);
                        review.setImageResource(R.drawable.icon_lives_live);
                        break;
                    case 3:
                        //结束
                        review.setVisibility(View.VISIBLE);
                        review.setImageResource(R.drawable.icon_lives_end);
                        break;
                    default:
                        break;
                }
            }
        };

        listview.setAdapter(mAdapter);
        mPresenter.getDatas(sceneId, type);
    }

    @Override
    protected void setListener() {
        //重载
        loadMask.setOnReloadListener(v -> {
            loadMask.setReloadButtonText("加载中...");
            sceneId = "0";
            mPresenter.getDatas(sceneId, type);
        });

        //刷新
        refresh.setOnRefreshListener(refreshlayout -> {
            sceneId = "0";
            mPresenter.getDatas(sceneId, type);
        });

        refresh.setOnLoadMoreListener(refreshLayout -> mPresenter.getDatas(sceneId, type));

        //列表点击
        listview.setOnItemClickListener((parent, view, position, id) -> {
            ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.TELETEXTDETAIL);
            if (mDataList.get(position).getIsPsw() == 1) {
                mDialog = new OtherDialog.Builder(TeleTextListActivity.this)
                        .setContentView(R.layout.live_dialog_check_code)
                        .setText(R.id.title, "请输入直播密码")
                        .setDismissButton(R.id.negative_btn)
                        .setCancelable(false)
                        .setCanceledOnTouchOutside(false)
                        .bundleInputWithoutDismissListener(R.id.code, R.id.positive_btn, new OtherDialog.InputListener() {
                            @Override
                            public void onClick(View view, String message) {
                                if (StringUtils.isNotEmpty(message)) {
                                    showLoading();
                                    mPresenter.checkCode(mDataList.get(position).getId() + "", message, mDataList.get(position));
                                    mDialog.dismiss();
                                } else {
                                    showToast("请输入密码");
                                }
                            }
                        });
                mDialog.show();
            } else {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    //预告
                    Bundle bundle = new Bundle();
                    bundle.putString("id", mDataList.get(position).getId() + "");
                    RouterManager.router(ARouterPathConstant.TELE_VIDEO_ACTIVITY, bundle);
                } else {
                    Toasty.normal(TeleTextListActivity.this, "此功能暂时不支持在当前手机系统版本上使用！").show();
                }
            }


        });

        backBtn.setOnClickListener(v -> finish());
    }


    /**
     * 设置列表数据
     *
     * @param beanList
     */
    @Override
    public void setDatas(List<TeleTextBean> beanList, boolean isMore) {

        loadMask.setReloadButtonText("点击重试~~");
        loadMask.setStatus(LoadingLayout.Success);

        if (isMore) {
            refresh.finishLoadMore();
        } else {
            refresh.finishRefresh();
            mDataList.clear();
        }
        sceneId = beanList.get(beanList.size() - 1).getId() + "";

        mDataList.addAll(beanList);

        mAdapter.notifyDataSetChanged();
    }

    /**
     * 出错
     *
     * @param msg
     */
    @Override
    public void setError(String msg, boolean isMore) {
        if (isMore) {
            refresh.finishLoadMore();
            showToast(msg, 4);
        } else {
            refresh.finishRefresh();
            loadMask.setStatus(LoadingLayout.Error);
            loadMask.setReloadButtonText("点击重试~~");
            loadMask.setErrorText(msg);
        }

    }

    /**
     * 无内容
     *
     * @param msg
     */
    @Override
    public void setEmpty(String msg, boolean isMore) {
        if (isMore) {
            refresh.finishLoadMore();
            showToast(msg, 4);
        } else {
            refresh.finishRefresh();
            loadMask.setReloadButtonText("点击重试~~");
            loadMask.setStatus(LoadingLayout.Empty);
            loadMask.setEmptyText(msg);
        }

    }

    /**
     * 无网络
     *
     * @param msg
     */
    @Override
    public void setNetError(String msg, boolean isMore) {
        if (isMore) {
            refresh.finishLoadMore();
            showToast(msg, 4);
        } else {
            refresh.finishRefresh();
            loadMask.setReloadButtonText("点击重试~~");
            loadMask.setStatus(LoadingLayout.No_Network);
            loadMask.setNoNetworkText(msg);
        }

    }

    @Override
    public void checkResult(boolean isSuccess, TeleTextBean bean) {
        dismissLoading();
        if (isSuccess) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                //预告
                Bundle bundle = new Bundle();
                bundle.putString("id", bean.getId() + "");
                RouterManager.router(ARouterPathConstant.TELE_VIDEO_ACTIVITY, bundle);
            } else {
                Toasty.normal(TeleTextListActivity.this, "此功能暂时不支持在当前手机系统版本上使用！").show();
            }
        } else {
            showToast("密码错误");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //umeng
        MobclickAgent.onPageStart("全媒体列表");
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        //umeng
        MobclickAgent.onPageEnd("全媒体列表");
        MobclickAgent.onPause(this);
    }
}
